<template>
  <div class="page">
    <StoreChoice
      ref="storeChoice"
      :isReset="isReset"
      :current="[]"
      :sourceData="currentStore"
      :multipleChoice="false"
      @listenToStoreSelect="getSelectStoreValue"
      :statusFilter="false"
      :hasTotal="false"
    />
    <div class="scroll-view">
      <customHeader @leftCallBack="goBack" middleTitle="活动管理"></customHeader>
			<mt-navbar v-model="activityStatus" class="navbar">
        <mt-tab-item id="0">未开始</mt-tab-item>
        <mt-tab-item id="1">进行中</mt-tab-item>
        <mt-tab-item id="2">已结束</mt-tab-item>
      </mt-navbar>
      <div class="page-body">
				<div ref="wrapper" style="height:100%">
					<mt-loadmore :top-method="loadTop" :topDistance="20" :auto-fill="false" ref="loadmore" @top-status-change="handleTopChange" style="height:100%">
						<ul class="form-style-top" v-infinite-scroll="loadMore" infinite-scroll-disabled="loading" infinite-scroll-distance="30">
							<div class="more-list" v-for="(item,index) in list" :key="index">
                <div class="more-list_tag">{{['满减券','消费赠券','拉新券','引流券'][item.marketActivityType-1]}}</div>
								<div class="more-list_content">
									<div class="more-list_l">
										<p v-html="formatDiscount(item)"></p> 
										<p class="f24">满{{item.useLimit}}元可用</p>
									</div>
									<div class="more-list_r">
										<!-- <p class="f32"><strong>{{item.voucherName}}</strong></p> -->
										<p class="f32">{{item.voucherName}}</p>
										<p class="f24">有效期：{{formatDate(item)}}</p>
									</div>
								</div>
								<div class="more-list_record f30" v-if="activityStatus!=0">
									<div><p>发放量</p>{{item.grantNumber||0}}</div>
									<div><p>核销量</p>{{item.verifyNumber||0}}</div>
									<div><p>核销率</p>{{item.verifyRatio||0}}%</div>
									<div><p>带来收入(元)</p>{{item.incomeAmount||0}}</div>
									<div><p>带来订单量</p>{{item.orderNumber||0}}</div>
									<div><p>笔单价(元)</p>{{item.avgAmount||0}}</div>
								</div>
								<div class="more-list_btn">
									<div class="btn" @click="handleOperate(item, 1)" v-if="activityStatus==0">立即开始</div>
									<div class="btn" @click="handleShare(item)" v-if="activityStatus==1">活动推广</div>
									<div class="btn" @click="handleOperate(item, 2)" v-if="activityStatus==1">活动下架</div>
									<div class="btn" @click="handleRelaunch(item)" v-if="activityStatus==2">再发一次</div>
									<!-- <div class="btn" @click="handleRelaunch(item)">再发一次</div> -->
								</div>
							</div>
						</ul>
						<p v-show="topStatus!='loading'&&loading" class="page-infinite-loading">
							<mt-spinner style="display:inline-block" type="fading-circle"></mt-spinner>
						</p>
						<div v-show="noMore&&!hasError" class="no-more">已经全部加载完毕</div>
						<noData msg="暂无数据" v-if="hasError" />
					</mt-loadmore>
				</div>
      </div>
			<mt-button class="w100" @click="$router.push('/couponMarketing/couponList?stack=2')" type="primary">创建活动</mt-button>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import {Toast, MessageBox} from "mint-ui";
import StoreChoice from "@/components/StoreChoice/StoreChoice";
import customHeader from "@/components/header/header";
import noData from "@/components/noData/noData";
import jsBridge from "@/tools/jsBridge.js";

export default {
  components: {
    customHeader,
    StoreChoice,
		noData
  },
  data() {
    return {
      isReset: true,
			activityStatus: "1",
			pageNo: 1,
      pageSize: 10,
      noMore: false,
      loading: false,
      list: [],
      hasError: false,
      topStatus: "",
      currentStore: {}
    };
	},
	watch: {
    activityStatus(val) {
      this.loadTop();
    }
  },
  methods: {
    goBack() {
      if(this.$route.query.stack) {
        this.$router.go(-3);
      }else {
        this.$router.back();
      }
    },
    handleRelaunch(item) {
      item.id = item.marketActivityType;
      this.$router.push({
        path: '/couponMarketing/couponEdit',
        query: item
      });
    },
    getSelectStoreValue(value) {
      let store = value && value[0];
      if(store.selectKey && store.selectKey!="all") {
        this.isReset = new Date();
        this.share(store.selectKey, store.selectName);
      }
    },
		formatDiscount(item) {
      let num = item.voucherType==1 ? item.facePrice : item.discount;
      let arr = (''+num).split('.');
      let html = arr.length==1 ? `<strong>${arr[0]}</strong>` : `<strong>${arr[0]}</strong>.${arr[1]}`;
      return item.voucherType==1 ? `<span>¥</span>${html}` : html+'<span>折</span>';
		},
		formatDate(item) {
      let txt;
      // if(moment(item.activityStartTime).add(20, 'years').valueOf() == item.activityEndTime) {
      if(moment(item.activityEndTime).year()-moment(item.activityStartTime).year()>18) {
        txt = `${moment(+item.activityStartTime).format('YYYY-MM-DD')} 至 长期有效`
      }else {
        txt = `${moment(+item.activityStartTime).format('YYYY-MM-DD')} 至 ${moment(+item.activityEndTime).format('YYYY-MM-DD')}`
      }
			return txt;
    },
    share(shopId, shopName) {
      this.ajax({
        url: 'newapp/activity/createPromotionPic.do',
        type: "get",
        data: {
          activityId: this.activityId,
          shopId: shopId,
          shopName: shopName
        },
        controlLoading: true
      }).then(res=> {
        if(res.success) {
          jsBridge.shardBySystem({imageBase64Str: '@'+res.resultObject})
        }else {
          Toast(res.msg)
        }
      });
    },
		handleShare(item) {
      this.activityId = item.activityId;
      let grantShops = item.grantShops || [];
      if(grantShops.length==1) {
        this.share(grantShops[0].shopId, grantShops[0].shopName);
        return;
      }
      grantShops.forEach(item=> {
        item.selectKey = item.shopId;
        item.selectName = item.shopName;
      });
      this.currentStore = {
        '发放门店': grantShops
      }
      this.$refs.storeChoice.popupShow();
		},
		handleOperate(item, type) {
      let func = ()=> {
        this.ajax({
          url: 'newapp/activity/setActivityStatus.do',
          type: "post",
          data: {
            activityStatus: type,
            activityId: item.activityId
          },
          controlLoading: true
        }).then(res=> {
          if(res.success) {
            this.loadTop();
          }else {
            Toast(res.msg||'服务错误');
          }
        });
      };
      if(type==1) {
        func();
        return;
      }
			MessageBox.confirm('确定下架该活动?').then(action => {
        func();
			});
		},
		handleTopChange(status) {
			this.topStatus = status;
    },
    resetList() {
      this.pageNo = 1;
      this.list = [];
      this.noMore = false;
    },
    loadTop() {
      this.resetList();
      this.loadMore();
		},
		loadMore() {
      if(this.loading || this.noMore) {
        return;
      }
      this.getData();
		},
		getData() {
      this.loading = true;
      let params = {
        activityStatus: this.activityStatus,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      }
      this.ajax({
        url: 'newapp/activity/queryActivityPageData.do',
				type: "post",
				data: params,
        controlLoading: false
      }).then(res=> {
        this.loading = false;
        if(this.activityStatus!=params.activityStatus) {
          this.list = [];
        }
				if(res.success) {
          let data = res.resultObject || {};
          data.dataList = data.dataList || [];
					this.list = this.list.concat(data.dataList);
					if(data.dataAllCount) {
            this.noMore = data.dataList.length < this.pageSize ? true : false;
          }else {
            this.noMore = true;
          }
          this.pageNo++;
          this.hasError = !this.list.length;
				}else {
          this.noMore = true;
          Toast(res.msg||'服务错误');
        }
        this.hasError = !this.list.length;
        this.$refs.loadmore && this.$refs.loadmore.onTopLoaded && this.$refs.loadmore.onTopLoaded();
			}).catch(err => {
				this.loading = false;
				this.noMore = true;
				this.hasError = !this.list.length;
				this.$refs.loadmore && this.$refs.loadmore.onTopLoaded && this.$refs.loadmore.onTopLoaded();
			});
    }
  }
};
</script>

<style lang='scss' scoped>
@import "../../style/public";
.navbar /deep/ {
  .mint-tab-item.is-selected {
		border-bottom: none;
    position: relative;
    margin-bottom: 0;
		&:after {
			content: ' ';
			display: block;
			position: absolute;
			bottom: 0;
			left: 30%;
			width: 40%;
			height: 2px;
			background-color: #26a2ff;
		}
	}
}
.more-list {
	background-color: #fff;
	@include remCalc(margin-top, 20);
	@include thin-border(true, false);
	&_tag {
		position: absolute;
		color: #459DFF;
    background-color: #ecf5ff;
		right: 0;
		text-align: center;
		@include remCalc(width, 125);
		@include remCalc(height, 44);
		@include remCalc(line-height, 42);
		@include remCalc(font-size, 24);
		@include remCalc(border-radius, 0, 0, 0, 10);
	}
	&_content {
		display: flex;
		color: #333;
		box-sizing: border-box;
		@include remCalc(min-height, 165);
		@include remCalc(padding, 20, 0);
		@include thin-border(false, false);
		&:after {
			top: 100%;
			right: 0;
			width: auto;
			@include remCalc(left, 30);
		}
	}
	&_l {
		display: flex;
		flex-direction: column;
		justify-content: center;
		@include remCalc(width, 160);
    @include remCalc(padding-left, 30);
    .f24 {
      position: relative;
      @include remCalc(top, -3);
    }
	}
	&_r {
		height: 100%;
		flex: 1;
    @include remCalc(padding-right, 125);
    p:nth-of-type(1) {
      @include remCalc(height, 88);
      word-break: break-all;
		}
		p:nth-of-type(2) {
			color: #999;
		}
	}
	&_btn {
		text-align: right;
		@include remCalc(padding, 20, 30);
		.btn {
			@include remCalc(margin-left, 30);
		}
	}
	.more-list_record {
		display: flex;
		flex-wrap: wrap;
		text-align: center;
		@include remCalc(padding-bottom, 30);
		@include thin-border(false, false);
		&:after {
			top: 100%;
			right: 0;
			width: auto;
			@include remCalc(left, 30);
		}
		>div {
			flex-basis: 33.3333%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			p {
				color: #999;
				@include remCalc(font-size, 28);
				@include remCalc(margin, 30, 0, 10);
			}
		}
	}
}
.btn {
	display: inline-block;
	color: #459DFF;
	text-align: center;
	border: 1px solid #459DFF;
	@include remCalc(width, 200);
	@include remCalc(height, 58);
	@include remCalc(line-height, 58);
	@include remCalc(border-radius, 100);
	@include remCalc(font-size, 28);
}
</style>
<style lang='scss'>
@import "../../style/public";
.more-list {
	&_l {
		p:nth-of-type(1) {
      @include remCalc(font-size, 36);
      @include remCalc(height, 88);
      @include remCalc(line-height, 88);
			strong {
        @include remCalc(font-size, 55);
        line-height: 1;
        font-weight: normal;
      }
      span {
        @include remCalc(font-size, 28);
      }
		}
	}
}
</style>